var wgtWaiting = null;
var down_version_url = DOWN_APP_API;
var down_name = '/app.apk'
var CHECK_VERSION_URL = CHECK_VERSION_API;
var lastTime = 0;

function checkVersion() {
    wgtWaiting = plus.nativeUI.showWaiting("检查更新中。。。");
    Resource.get(CHECK_VERSION_URL, {}, function (res) {
        wgtWaiting.close();
        var server_version = res.version;
        if (!isUpdate(LOCAL_APP_VERSION, server_version)) {
            plus.nativeUI.closeWaiting();
            mui.alert("当前已经是最新版本！");
            return;
        }
        var btnArray = ['确定', '取消'];
        mui.confirm('是否需要升级到最新版本？', '提示', btnArray, function (e) {
            if (e.index == 0) {
                // 下载文件
                downAppVerson(down_version_url + server_version + down_name);
            }
        })
    }, function (error) {
        plus.nativeUI.close();
    })

};

function downAppVerson(url) {
    lastTime = Date.now();
    var wgtOption = {filename: "_doc/update/" + Date.now()+'/', retry: 5};
    var task = plus.downloader.createDownload(url, wgtOption, function (download, status) {
        if (status == 200) {
            installApp(download.filename);
        } else {
            mui.alert("应用升级失败！");
            wgtWaiting.close();
        }
    });
    task.addEventListener("statechanged", function (download, status) {
        switch (download.state) {
            case 2:
                vm.updateProgress = "1%";
                break;
            case 3:
                var percent = download.downloadedSize / download.totalSize * 100;
                if(Date.now() - lastTime > 1000*1){
                    lastTime = Date.now();
                    vm.updateProgress =  parseInt(percent) + "%";
                }
                break;
            case 4:
                // wgtWaiting.setTitle("下载完成");
                break;

        }
    },false);
    console.log(JSON.stringify(task));
    task.start();
    return task;
}

function installApp(path) {
    wgtWaiting.setTitle("开始安装");
    plus.runtime.install(path, {}, function (wgtinfo) {
        wgtWaiting.close();
        mui.alert("更新完成，须重启应用！", function () {
            plus.runtime.restart();
        });
    }, function (error) {
        wgtWaiting.close();
        console.log('关闭 watiingg');
        mui.alert("应用更新失败！\n" + error.message);
    });
   // var wgtWaiting = null;
};


//计算版本号大小,转化大小
function toNum(a) {
    var a = a.toString();
    var c = a.split('.');
    var num_place = ["", "0", "00", "000", "0000"], r = num_place.reverse();
    for (var i = 0; i < c.length; i++) {
        var len = c[i].length;
        c[i] = r[len] + c[i];
    }
    var res = c.join('');
    return res;
}

//检测插件版本号是否需要更新
function isUpdate(a, b) {
    var a = toNum(a);
    var b = toNum(b);
    if (a == b) {
        console.log("版本号相同！版本号为:" + a);
        return false;
    } else if (a > b) {
        console.log("版本号" + a + "是新版本!");
        return false;
    } else {
        console.log("版本号" + b + "是新版本!");
        return true;
    }
}
